package com.compass.doctor.ui

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import androidx.activity.viewModels
import androidx.core.content.ContentProviderCompat.requireContext
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
import com.compass.doctor.R
import com.compass.doctor.base.BaseVBActivity
import com.compass.doctor.databinding.ActivityDoctorMainBinding
import com.compass.doctor.service.LocalRecordingService
import com.compass.doctor.ui.chat.util.CustomUIConfig.configCallKit
import com.compass.doctor.ui.chat.util.CustomUIConfig.configChatKit
import com.compass.doctor.ui.chat.util.CustomUIConfig.configConversation
import com.compass.doctor.ui.chat.util.CustomUIConfig.initChatCustomAttach
import com.compass.doctor.ui.chat.util.CustomUIConfig.initChatCustomViewHolder
import com.compass.doctor.ui.home.fragment.NewHomeFragment
import com.compass.doctor.ui.message.fragment.MyConversationFragment
import com.compass.doctor.ui.mine.fragment.MineFragment
import com.compass.doctor.ui.patient.fragment.PatientFragment
import com.compass.doctor.ui.patient.viewmodel.VideoCallViewModel
import com.compass.framework.adapter.ViewPage2FragmentAdapter
import com.compass.framework.constant.KEY_INDEX
import com.compass.framework.constant.LOGIN_FAILURE
import com.compass.framework.constant.REFRESH_USER
import com.compass.framework.model.UpdateInfo
import com.compass.framework.toast.TipsToast
import com.compass.framework.update.manager.DownloadManager
import com.compass.framework.utils.DeviceInfoUtils
import com.compass.framework.utils.LiveDataBus
import com.compass.framework.utils.LogUtil
import com.compass.framework.utils.StatusBarSettingHelper
import com.compass.framework.utils.getColorFromResource
import com.netease.nimlib.sdk.NIMClient
import com.netease.nimlib.sdk.Observer
import com.netease.nimlib.sdk.RequestCallback
import com.netease.nimlib.sdk.StatusCode
import com.netease.nimlib.sdk.auth.AuthService
import com.netease.nimlib.sdk.auth.AuthServiceObserver
import com.netease.nimlib.sdk.auth.OnlineClient
import com.netease.yunxin.kit.corekit.im.repo.SettingRepo


/**

 * @desc   医生模块主页
 */
class MainActivity : BaseVBActivity<ActivityDoctorMainBinding>() {

    private val mainViewModel: MainViewModel by viewModels()
    private var fragments: ArrayList<Fragment> = ArrayList()

    private lateinit var viewPageAdapter: ViewPage2FragmentAdapter
    private lateinit var homeFragment: NewHomeFragment
    private lateinit var ainConversationFragment: MyConversationFragment
    private lateinit var patientFragment: PatientFragment
    private lateinit var mineFragment: MineFragment


    companion object {
        fun start(context: Context, index: Int = 0) {
            val intent = Intent(context, MainActivity::class.java)
            intent.putExtra(KEY_INDEX, index)
            context.startActivity(intent)
        }
    }


    override fun initView(savedInstanceState: Bundle?) {
        StatusBarSettingHelper.setStatusBarTranslucent(this)
        StatusBarSettingHelper.statusBarLightMode(this@MainActivity, true)
        SettingRepo.setHandsetMode(false);
        setBride(0) //清空一次角标
        initFragment()
        DeviceInfoUtils.init(this)
        //去除自带的选中颜色,去除后文字和图片选择效果就是跟我们自定义的效果一样
        mBinding.navView.itemIconTintList = null
        viewPageAdapter = ViewPage2FragmentAdapter(supportFragmentManager, lifecycle, fragments)
        mBinding.viewpager2.adapter = viewPageAdapter
        mBinding.viewpager2.isUserInputEnabled = false//禁止viewPage滑动
        mBinding.viewpager2.setCurrentItem(0, false)
        mBinding.viewpager2.offscreenPageLimit = fragments.size
        mBinding.viewpager2.registerOnPageChangeCallback(object :
            ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                when (position) {
                    0 -> {
                        mBinding.navView.selectedItemId = R.id.navi_home
                    }

                    1 -> {
                        mBinding.navView.selectedItemId = R.id.navi_message
                    }

                    2 -> {
                        mBinding.navView.selectedItemId = R.id.navi_patient
                    }

                    3 -> {
                        mBinding.navView.selectedItemId = R.id.navi_mine
                    }
                }
            }
        })
        mBinding.navView.setOnItemSelectedListener { item ->

            when (item.itemId) {
                R.id.navi_home -> {
                    mBinding.viewpager2.setCurrentItem(0, false)
                    return@setOnItemSelectedListener true
                }

                R.id.navi_message -> {
                    mBinding.viewpager2.setCurrentItem(1, false)
                    return@setOnItemSelectedListener true
                }

                R.id.navi_patient -> {
                    mBinding.viewpager2.setCurrentItem(2, false)
                    return@setOnItemSelectedListener true
                }

                R.id.navi_mine -> {
                    if (mineFragment.isAdded) mineFragment.getWallet()
                    mBinding.viewpager2.setCurrentItem(3, false)
                    return@setOnItemSelectedListener true
                }

                else -> {
                    false
                }
            }
        }
    }

    private fun initFragment() {
        homeFragment = NewHomeFragment()
        fragments.add(homeFragment)

        ainConversationFragment = MyConversationFragment()
        fragments.add(ainConversationFragment)

        patientFragment = PatientFragment()
        fragments.add(patientFragment)

        mineFragment = MineFragment()
        fragments.add(mineFragment)

        initConversationFragment(ainConversationFragment)
    }


    override fun initData() {
        loadChatConfig()
        //设置为空闲

        mainViewModel.getUserInfo()
        mainViewModel.getAppVersion()
        SettingRepo.setShowReadStatus(false)
        NIMClient.getService(AuthServiceObserver::class.java)
            .observeOnlineStatus(onlineStatusObserver, true)
//        NIMClient.getService(AuthServiceObserver::class.java)
//            .observeLoginSyncDataStatus()
//        NIMClient.getService(AuthServiceObserver::class.java)
//            .observeOtherClients(otherClientsObserver,true)
        mainViewModel.patientLiveData.observe(this) {
            mBinding.viewpager2.setCurrentItem(2, false)
        }
        mainViewModel.versionLiveData.observe(this) {
            it?.let { updateInfo ->
                updateTest(updateInfo)
            }

        }
        LiveDataBus.get().with(REFRESH_USER, String::class.java).observe(this) {
            mainViewModel.getUserInfo()
        }

//        mainViewModel.onlineOtherClientLiveData.observe(this){
//            //监听到有其它设备登录的情况下，则自己退出
//           val imLoginState = mainViewModel.imLoginStateLiveData.value
//           if(imLoginState == StatusCode.LOGINED){
//               showToast("账号已在其他端登录")
//               NIMClient.getService(AuthService::class.java).logout()
//               LiveDataBus.get().with(LOGIN_FAILURE).postValue(LOGIN_FAILURE)
//           }
//        }
//
//        mainViewModel.imLoginStateLiveData.observe(this){
//            //自己登录成功以后，如果还有其它设备登录的情况，则将其它设备踢下线
//            val onlineOtherClient =  mainViewModel.onlineOtherClientLiveData.value
//            if(onlineOtherClient!=null && it.value == StatusCode.LOGINED.value){
//                kickOtherClient(onlineOtherClient)
//            }
//        }
    }


    private val onlineStatusObserver = Observer<StatusCode> { statusCode ->
        LogUtil.d("接收到在线状态变化回调$statusCode")
//        mainViewModel.imLoginStateLiveData.postValue(statusCode)
        if (statusCode == StatusCode.KICKOUT) {
            showToast("账号已在其他端登录")
            LiveDataBus.get().with(LOGIN_FAILURE).postValue(LOGIN_FAILURE)
        } else if (statusCode == StatusCode.LOGINED) {
//            当前账号登录成功，则踢出其它在线的设备
//            mainViewModel.imLoginStateLiveData.postValue(StatusCode.LOGINED)
//            val  onlineClient = mainViewModel.onlineOtherClientLiveData.value
//            if(onlineClient!=null){
//                kickOtherClient(onlineClient)
//            }
        }
        //被踢下线的逻辑
        else if (statusCode == StatusCode.KICK_BY_OTHER_CLIENT) {
            //被其它账号踢的回调
            showToast("账号已在其他端登录")
            NIMClient.getService(AuthService::class.java).logout()
            LiveDataBus.get().with(LOGIN_FAILURE).postValue(LOGIN_FAILURE)
        }
//        后续再处理登录在新状态异常问题
//        LogUtil.e("userStatus=$statusCode==自己查看code说明")
    }
    private val otherClientsObserver = Observer<List<OnlineClient>>() { onlineClients ->
        if (onlineClients == null || onlineClients.isEmpty()) {
            return@Observer
        }
        mainViewModel.onlineOtherClientLiveData.postValue(onlineClients[0])

//        showToast("账号已在其他端登录")
//        NIMClient.getService(AuthService::class.java).logout()
//        LiveDataBus.get().with(LOGIN_FAILURE).postValue(LOGIN_FAILURE)
//        mainViewModel.onlineClient.postValue(onlineClient)
    }

    /**
     * 将其它客户端踢下线
     */
    private fun kickOtherClient(onlineClient: OnlineClient) {
        NIMClient.getService(AuthService::class.java).kickOtherClient(onlineClient)
            .setCallback(object :
                RequestCallback<Void> {
                override fun onSuccess(result: Void?) {
                    LogUtil.d("other devices are successfully kicked. ")
                }

                override fun onFailed(code: Int) {
                    LogUtil.d("other devices are failed kicked. ")
                    LogUtil.d("failed：code $code ")
                }

                override fun onException(exception: Throwable?) {
                    LogUtil.d("other devices are exception kicked. ")
                }

            })
    }

    /**
     * 配置云信自定义UI、消息
     */
    private fun loadChatConfig() {
        //自定义消息设置
        initChatCustomAttach()
        initChatCustomViewHolder()
        configChatKit(this)
        //会话列表配置信息
        configConversation()
        //音视频通配置信息
        configCallKit()
    }


    private fun initConversationFragment(conversation: MyConversationFragment) {
        conversation.setConversationCallback() {
            setBride(it)
        }
    }


    /**
     * 设置红点消息
     */
    private fun setBride(messageNumber: Int) {
        //如果设置为2，number设置为15
        var bride = mBinding.navView.getOrCreateBadge(R.id.navi_message)
        bride.backgroundColor = getColorFromResource(R.color.color_f24957)//设置角标背景色
        bride.maxCharacterCount = 3//最多显示几位数字
        bride.isVisible = messageNumber > 0
        bride.number = messageNumber

        setBadgeNum(messageNumber)

    }

    /**
     * 华为/荣耀(8.0之前) 桌面角标
     */
    private fun setBadgeNum(num: Int) {
        try {
            val bundle = Bundle()
            bundle.putString("package", "com.compass.qihuang")
            bundle.putString("class", "com.compass.qihuang.splash.SplashActivity")
            bundle.putInt("badgenumber", num)
            contentResolver.call(
                Uri.parse("content://com.huawei.android.launcher.settings/badge/"), "change_badge",
                null,
                bundle
            )
        } catch (e: Exception) {

        }
    }


    private val apkName = "medical.apk"
    private var manager: DownloadManager? = null
    private fun updateTest(updateInfo: UpdateInfo) {
        manager = DownloadManager.Builder(this).run {
            apkUrl(updateInfo.url)
            apkName(apkName)
            smallIcon(R.mipmap.ic_logo)
            forcedUpgrade(true)
            //设置了此参数，那么内部会自动判断是否需要显示更新对话框，否则需要自己判断是否需要更新
            apkVersionCode(updateInfo.versionCode)
            //同时下面三个参数也必须要设置
            apkVersionName(updateInfo.apkVersionName)
            apkSize(updateInfo.apkSize)
            apkDescription(updateInfo.apkDescription)
                .apkMD5("")
            //省略一些非必须参数...
            build()
        }
        manager?.download()
    }


    private var mLastClickBackTime: Long = 0 //上次点击back键的时间
    override fun onBackPressed() {

        val curTime = System.currentTimeMillis()
        if (curTime - mLastClickBackTime > 2000) {
            mLastClickBackTime = curTime
            TipsToast.showTips(com.compass.framework.R.string.base_app_exit_one_more_press)
            return
        }
        super.onBackPressed()
    }

    override fun onPause() {
        super.onPause()
//        startRecordingService()
    }


    private fun startRecordingService() {
//        if (joined) {
//            // 创建一个 intent
//            val intent = Intent(this, LocalRecordingService::class.java)
//            // 根据 Android 版本，选择合适的方式启动前台服务
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//                // 对于 Android 8 及以上版本，使用 startForegroundService 来启动服务
//                startForegroundService(intent)
//            } else {
//                // 对于 Android 8 以下版本，使用 startService 来启动服务
//                startService(intent)
//            }
//        }

        // 创建一个 intent
        val intent = Intent(this, LocalRecordingService::class.java)
        // 根据 Android 版本，选择合适的方式启动前台服务
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // 对于 Android 8 及以上版本，使用 startForegroundService 来启动服务
            startForegroundService(intent)
        } else {
            // 对于 Android 8 以下版本，使用 startService 来启动服务
            startService(intent)
        }

    }


    override fun onDestroy() {
        super.onDestroy()
        NIMClient.getService(AuthServiceObserver::class.java)
            .observeOnlineStatus(onlineStatusObserver, false)
        NIMClient.getService(AuthServiceObserver::class.java)
            .observeOtherClients(otherClientsObserver, false)
    }
}